package com.yun.blog.utils;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ArrayUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;

/**
 * @author : simple
 * @title : HttpUtils
 * @projectName : dantouBlog-back
 * @description : httpClient 工具类
 * @email : yun_simple@163.com
 * @date : 2023/6/5下午5:30
 */

public class HttpUtils {

    /**
     * http GET 请求，返回响应字符串
     *
     * @param scheme http、https
     * @param host   localhost
     * @param port   -1 或 其他端口
     * @param path   url路径
     * @param params 参数
     * @return String
     * @author yun
     * @date 2023/6/5 下午6:30
     */
    public static String get(String scheme, String host, int port, String path, Header[] headers, List<NameValuePair> params) {
        // 构建uri
        try {
            URI uri = new URIBuilder().setScheme(scheme)
                    .setHost(host)
                    .setPort(port)
                    .setPath(path)
                    .setParameters(params).build();
            return get(uri, headers);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 带参数的get请求
     *
     * @param url    url
     * @param params 参数
     * @return String
     * @author yun
     * @date 2023/6/5 下午9:59
     */
    public static String get(String url, Header[] headers, List<NameValuePair> params) {
        try {
            URI uri;
            if (params != null) {
                uri = new URIBuilder(url).setParameters(params).build();
            } else {
                uri = new URIBuilder(url).build();
            }
            return get(uri, headers);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 没有参数或者参数直接在url中的get请求
     *
     * @param url url
     * @return String
     * @author yun
     * @date 2023/6/5 下午9:58
     */
    public static String get(String url, Header[] headers) {
        return get(url, headers, null);
    }


    /**
     * get请求
     *
     * @param uri 请求地址
     * @return String
     * @author yun
     * @date 2023/6/5 下午8:27
     */
    public static String get(URI uri, Header[] headers) {
        // 创建自动关闭流的客户端
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 构建get请求
            HttpGet httpGet = new HttpGet(uri);
            // 设置请求头，无需判空，底层判断过
            httpGet.setHeaders(headers);
            // 执行get请求，得到响应
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            return body2Str(httpResponse);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * get请求
     *
     * @param url 请求地址
     * @return String
     * @author yun
     * @date 2023/6/5 下午8:27
     */
    public static String get(String url) {
        return get(url,null);
    }


    /**
     * post请求
     *
     * @param uri    uri
     * @param params 任意参数，对象或map
     * @return String
     * @author yun
     * @date 2023/6/5 下午10:12
     */
    public static String post(URI uri, Object params, Header[] headers) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(uri);
            // 设置请求头
            if (!ArrayUtils.isEmpty(headers)) {
                httpPost.setHeaders(headers);
            } else {
                httpPost.setHeader("Content-Type", "application/json;charset=utf8");
            }
            // 设置参数
            if (params != null) {
                StringEntity stringEntity = new StringEntity(JSON.toJSONString(params), "UTF-8");
                httpPost.setEntity(stringEntity);
            }
            // 执行post请求
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            return body2Str(httpResponse);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 带参数post请求
     *
     * @param url    url
     * @param params 参数对象或map
     * @return String
     * @author yun
     * @date 2023/6/5 下午10:15
     */
    public static String post(String url, Object params, Header[] headers) {
        try {
            URI uri = new URIBuilder(url).build();
            return post(uri, params, headers);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public static String post(String url, Object params) {
        try {
            URI uri = new URIBuilder(url).build();
            return post(uri, params, null);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }


    /**
     * post请求
     *
     * @param url url
     * @return String
     * @author yun
     * @date 2023/6/5 下午10:15
     */
    public static String post(String url) {
        return post(url, null, null);
    }


    /**
     * 从请求响应中得到请求体字符串
     *
     * @param httpResponse 请求响应
     * @return String
     * @author yun
     * @date 2023/6/5 下午8:25
     */
    private static String body2Str(HttpResponse httpResponse) throws IOException {
        HttpEntity entity = httpResponse.getEntity();
        // 得到响应体
        InputStream content = entity.getContent();
        // 字节流转为字符流
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(content));
        StringBuilder stringBuilder = new StringBuilder();
        String s;
        // 循环读取字符流中的数据
        while ((s = bufferedReader.readLine()) != null) {
            stringBuilder.append(s);
        }
        // 返回字符流String
        return stringBuilder.toString();
    }


    public static void main(String[] args) {
        // String s = get("http://127.0.0.1:10000/api/blog/getTopBlogs");
        // System.out.println(s);

        HashMap<String, Object> params = new HashMap<>();
        params.put("searchText", "Mysql");
        params.put("pageNum", 1);
        params.put("pageSize", 10);

        BasicHeader basicHeader = new BasicHeader("Content-Type", "application/json;charset=utf8");
        // BasicHeader basicHeader = new BasicHeader("Content-Type", "application/x-www-form-urlencoded");
        Header[] headers = {basicHeader};
        String post = post("http://127.0.0.1:10000/api/blog/condition", params, headers);
        System.out.println(post);
    }
}
